package com.live.tools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.xmlpull.v1.XmlPullParser;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Xml;

public class LiveTools {

	/**
	 * Uri获取真实路径转换成File的方法
	 * 
	 * @param uri
	 * @param activity
	 * @return
	 */
	public static File uriToFile(Uri uri, Context context) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = context.getContentResolver().query(uri, proj, null, null, null);
		int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		String img_path = actualimagecursor.getString(actual_image_column_index);
		return new File(img_path);
	}

	/**
	 * Uri转换成Bitmap的方法
	 * 
	 * @param uri
	 * @param activity
	 * @return
	 * @throws FileNotFoundException
	 */
	public static Bitmap uriToBitmap(Uri uri, Context context) throws FileNotFoundException {
		ContentResolver cr = context.getContentResolver();
		return BitmapFactory.decodeStream(cr.openInputStream(uri));
	}

	/**
	 * 删文件（清缓存）
	 * 
	 * @param path
	 *            文件在/data/data/packageName/files 目录下，在rom中，packageName是你的包名
	 * @param txt
	 * @return
	 */
	public static boolean deleteFile(Context context) {

		File fileFolder = context.getFilesDir();
		File[] files = fileFolder.listFiles();
		for (int i = 0; i < files.length; i++) {
			files[i].delete();
		}

		return true;
	}

	/**
	 * 写文件
	 * 
	 * @param path
	 *            文件在/data/data/packageName/files 目录下，在rom中，packageName是你的包名
	 * @param txt
	 * @return
	 */
	public static boolean writeFile(Context context, String fileName, String txt) {
		try {
			OutputStream os = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			OutputStreamWriter osw = new OutputStreamWriter(os);
			osw.write(txt);
			osw.close();
			os.close();
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	/**
	 * 读文件
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static List<Map<String, Object>> readFile(Context context, String fileName) {

		List<Map<String, Object>> liveScoreList = new ArrayList<Map<String, Object>>();
		Map<String, Object> liveScore = null;
		try {

			File file = new File(fileName);
			if (file.exists()) {
				InputStream inputStream = context.openFileInput(fileName);

				XmlPullParser parser = Xml.newPullParser();
				parser.setInput(inputStream, "UTF-8");
				int eventType = parser.getEventType();
				String name = parser.getName();
				while (eventType != XmlPullParser.END_DOCUMENT) {

					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						// 文档开始事件,可以进行数据初始化处理
						break;
					case XmlPullParser.START_TAG:
						// 开始元素事件
						name = parser.getName();
						if (name.equalsIgnoreCase("detail")) {
							liveScore = new HashMap<String, Object>();
						}
						break;
					case XmlPullParser.END_TAG:
						// 结束元素事件
						name = parser.getName();
						if (name.equalsIgnoreCase("detail")) {
							liveScoreList.add(liveScore);
						}
						break;
					case XmlPullParser.TEXT:
						String text = parser.getText();
						// 内容元素事件
						if (name.equalsIgnoreCase("scoreId")) {
							liveScore.put("scoreId", text);
						} else if (name.equalsIgnoreCase("matchId")) {
							liveScore.put("matchId", text);
						} else if (name.equalsIgnoreCase("homeTeamScore")) {
							liveScore.put("homeTeamScore", text);
						} else if (name.equalsIgnoreCase("homeTeamIssucc")) {
							liveScore.put("homeTeamIssucc", text);
						} else if (name.equalsIgnoreCase("visitTeamScore")) {
							liveScore.put("visitTeamScore", text);
						} else if (name.equalsIgnoreCase("visitTeamIssucc")) {
							liveScore.put("visitTeamIssucc", text);
						} else if (name.equalsIgnoreCase("scoreTime")) {
							liveScore.put("scoreTime", text);
						} else if (name.equalsIgnoreCase("scoreAction")) {
							liveScore.put("scoreAction", text);
						}
						break;

					}
					eventType = parser.next();
				}
				inputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return liveScoreList;
	}

	/**
	 * 网络检测
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isConnect(Context context) {

		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			Log.v("error", e.toString());
		}
		return false;
	}

	/**
	 * 获取本机IP地址 （<uses-permission
	 * android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>）
	 * 
	 * @return
	 */
	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		return null;
	}

	/**
	 * 取得MAC地址 （<uses-permission
	 * android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>）
	 * 
	 * @return
	 */
	public static String getLocalMacAddress(Context context) {
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();
	}

	/**
	 * 将InputStream/OutputStream转换成string
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static String isToString(InputStream is) throws IOException {
		is = new GZIPInputStream(is);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		// 读取缓存
		byte[] buffer = new byte[2048];
		int length = 0;
		while ((length = is.read(buffer)) != -1) {
			bos.write(buffer, 0, length);// 写入输出流
		}
		is.close();// 读取完毕，关闭输入流

		// 根据输出流创建字符串对象
		return new String(bos.toByteArray(), "UTF-8");
	}
}
